﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace EasyCommonCore.Common
{
    /// <summary>
    /// 序列化帮助类
    /// </summary>
    public static class SerializerCommon
    {
        #region 对象序列号为Json字符串
        /// <summary>
        /// 对象序列号为Json字符串
        /// </summary>
        public static string ToJson(this object item)
        {
            if (item == null)
                return null;
            return JsonConvert.SerializeObject(item);
        }
        #endregion

        #region Json反序列化为对象
        /// <summary>
        /// Json反序列化为对象
        /// </summary>
        public static T ToObjectByDeserialize<T>(this string jsonString)
        {
            if (string.IsNullOrWhiteSpace(jsonString) || jsonString == "{}")
            {
                return default(T);
            }
            try
            {
                return JsonConvert.DeserializeObject<T>(jsonString);
            }
            catch (Exception)
            {
                return default(T);
            }
        }
        #endregion

        #region 转换为动态对象
        /// <summary>
        /// 转换为动态对象（索引器）
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static dynamic ToDynamicByDeserialize(this string jsonString)
        {
            if (string.IsNullOrWhiteSpace(jsonString) || jsonString == "{}")
            {
                return null;
            }
            try
            {
                return JsonConvert.DeserializeObject(jsonString) as JObject;
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 转换为动态对象（匿名类）
        /// </summary>
        /// <param name="jsonString"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public static dynamic ToDynamicByDeserialize<T>(this string jsonString, T t)
        {
            if (string.IsNullOrWhiteSpace(jsonString) || jsonString == "{}")
            {
                return null;
            }
            try
            {
                return JsonConvert.DeserializeAnonymousType(jsonString, t);
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion
    }
}
